const orderApi = require('../../api/order.js');
const drawQrcode = require('../../utils/weapp-qrcode.js'); // ✅ 引用封装版（别引 qrcode.min.js）

Page({
  data: {
    orders: [],
    showPayModal: false,
    currentOrderId: ''
  },

  onLoad() {
    this.loadOrders();
  },

  async loadOrders() {
    try {
      const res = await orderApi.queryAllByUser();
      console.log(res)
      if (res.code === 200) {
        // 只展示倒计时，不前端判断取消
        const orders = res.data.map(order => {
          if (order.status === 0 && order.cancelTime) {
            const cancelTime = new Date(order.cancelTime).getTime();
            const now = Date.now();
            order.remainingSeconds = Math.max(Math.floor((cancelTime - now) / 1000), 0);
          } else {
            order.remainingSeconds = 0;
          }
          return order;
        });
        this.setData({ orders });
      }
    } catch (err) {
      console.error('加载订单失败', err);
    }
  },

  async payOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    const amount = e.currentTarget.dataset.totalAmount;
    console.log(amount)

    try {
      const res = await orderApi.payOrder(orderId, amount, `订单支付 ${orderId}`);
      
      if (res.code === 200 && res.payUrl) {
        this.setData({ showPayModal: true, currentOrderId: orderId });

        // ✅ 直接生成二维码
        drawQrcode({
          canvasId: 'payCanvas',
          text: res.payUrl,
          width: 200,
          height: 200
        });
      }
    } catch (err) {
      console.error('支付失败', err);
    }
  },

  closePayModal() {
    this.setData({ showPayModal: false });
  },

  async deleteOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    await orderApi.deleteOrder(orderId);
    this.loadOrders();
  },

  viewDetails(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/orderDetail/orderDetail?id=${orderId}` });
  },

  getStatusText(status) {
    switch (status) {
      case 0: return '待支付';
      case 1: return '已支付';
      case 2: return '已取消';
      case 3: return '已完成';
      default: return '未知状态';
    }
  },

  formatTime(seconds) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}分${s}秒`;
  }
});
